/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clientGUI;

import fourbox.client.Client;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

/**
 *
 * @author Wiko Putrawan
 */
public class FourboxGUI extends javax.swing.JFrame {

    private URI https;
    public static boolean sync = true;
    public Client client;

    /**
     * Creates new form FourboxGUI
     */
    public FourboxGUI() {
        try {
            initComponents();
            client = new Client();
            client.initClient();

            Thread clientThread = new Thread(client);
            clientThread.start();

            if (!client.login) {
                logout.setEnabled(false);
                login.setEnabled(true);
            } else {
                logout.setEnabled(true);
                login.setEnabled(false);
            }

        } catch (IOException ex) {
            Logger.getLogger(FourboxGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        usernameLabel = new javax.swing.JLabel();
        usernameTextField = new javax.swing.JTextField();
        passwordLabel = new javax.swing.JLabel();
        passwordTextField = new javax.swing.JPasswordField();
        login = new javax.swing.JButton();
        logout = new javax.swing.JButton();
        fourboxMenuBar = new javax.swing.JMenuBar();
        fourboxMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        openWeb = new javax.swing.JMenuItem();
        changedFile = new javax.swing.JMenuItem();
        separator1 = new javax.swing.JPopupMenu.Separator();
        upToDate = new javax.swing.JMenuItem();
        separator2 = new javax.swing.JPopupMenu.Separator();
        syncing = new javax.swing.JMenuItem();
        separator3 = new javax.swing.JPopupMenu.Separator();
        preferences = new javax.swing.JMenuItem();
        separator4 = new javax.swing.JPopupMenu.Separator();
        exit = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("fourbox");
        setLocationByPlatform(true);

        usernameLabel.setText("Username:");

        passwordLabel.setText("Password:");

        login.setText("Log In");
        login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginActionPerformed(evt);
            }
        });

        logout.setText("Log Out");
        logout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutActionPerformed(evt);
            }
        });

        fourboxMenu.setText("Fourbox");

        jMenuItem1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jMenuItem1.setText("Open Fourbox folder");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        fourboxMenu.add(jMenuItem1);

        openWeb.setText("Launch Fourbox website");
        openWeb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openWebActionPerformed(evt);
            }
        });
        fourboxMenu.add(openWeb);

        changedFile.setText("Recently changed file");
        fourboxMenu.add(changedFile);
        fourboxMenu.add(separator1);

        upToDate.setText("All files up to date");
        upToDate.setEnabled(false);
        fourboxMenu.add(upToDate);
        fourboxMenu.add(separator2);

        syncing.setText("Pause syncing");
        syncing.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                syncingActionPerformed(evt);
            }
        });
        fourboxMenu.add(syncing);
        fourboxMenu.add(separator3);

        preferences.setText("Preferences...");
        preferences.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                preferencesActionPerformed(evt);
            }
        });
        fourboxMenu.add(preferences);
        fourboxMenu.add(separator4);

        exit.setText("Exit");
        exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionPerformed(evt);
            }
        });
        fourboxMenu.add(exit);

        fourboxMenuBar.add(fourboxMenu);

        setJMenuBar(fourboxMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(288, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(login)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(usernameLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(passwordLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(passwordTextField))))
                        .addGap(36, 36, 36))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(logout)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(logout)
                .addGap(68, 68, 68)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameLabel)
                    .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordLabel)
                    .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(login)
                .addContainerGap(96, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
        System.exit(WIDTH);
    }//GEN-LAST:event_exitActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        try {
            Desktop.getDesktop().open(new File(this.client.workingDir.toString()));
        } catch (IOException ex) {
            Logger.getLogger(FourboxGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void openWebActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openWebActionPerformed
        try {
            try {
                Desktop.getDesktop().browse(new URI("http://localhost/FourBoxWeb/"));
            } catch (URISyntaxException ex) {
                Logger.getLogger(FourboxGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(FourboxGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_openWebActionPerformed

    private void syncingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_syncingActionPerformed
        sync = !sync;
        if (sync) {
            syncing.setText("Pause syncing");
        } else {
            syncing.setText("Resume syncing");
        }
    }//GEN-LAST:event_syncingActionPerformed

    private void preferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_preferencesActionPerformed
        JFrame pref = new FourboxPreferences(this);
        pref.setVisible(true);
    }//GEN-LAST:event_preferencesActionPerformed

    private void loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginActionPerformed

//        client.loginThread.interrupt();
        try {
            client.doLogin(usernameTextField.getText(), passwordTextField.getText());
            try {          
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(FourboxGUI.class.getName()).log(Level.SEVERE, null, ex);
            }

            
            if (client.login) {
                login.setEnabled(false);
                logout.setEnabled(true);
            } else {
                
                client = new Client();
                client.initClient();

                Thread clientThread = new Thread(client);
                clientThread.start();
                
                login.setEnabled(true);
                logout.setEnabled(false);

            }
        } catch (IOException ex) {
            Logger.getLogger(FourboxGUI.class.getName()).log(Level.SEVERE, null, ex);
        }




    }//GEN-LAST:event_loginActionPerformed

    private void logoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoutActionPerformed
        // TODO add your handling code here:
        if (client.login) {
            try {
                client.doLogout();
            } catch (InterruptedException ex) {
                Logger.getLogger(FourboxGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(FourboxGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (client.connectionOn){
                logout.setEnabled(true);
                login.setEnabled(false);
            }else{
                logout.setEnabled(false);
                login.setEnabled(true);                
            }
            System.exit(0);
            
        }
    }//GEN-LAST:event_logoutActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FourboxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FourboxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FourboxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FourboxGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FourboxGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem changedFile;
    private javax.swing.JMenuItem exit;
    private javax.swing.JMenu fourboxMenu;
    private javax.swing.JMenuBar fourboxMenuBar;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JButton login;
    private javax.swing.JButton logout;
    private javax.swing.JMenuItem openWeb;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JPasswordField passwordTextField;
    private javax.swing.JMenuItem preferences;
    private javax.swing.JPopupMenu.Separator separator1;
    private javax.swing.JPopupMenu.Separator separator2;
    private javax.swing.JPopupMenu.Separator separator3;
    private javax.swing.JPopupMenu.Separator separator4;
    private javax.swing.JMenuItem syncing;
    private javax.swing.JMenuItem upToDate;
    private javax.swing.JLabel usernameLabel;
    private javax.swing.JTextField usernameTextField;
    // End of variables declaration//GEN-END:variables
}
